from dataconfig.file_config import FilePath
from logs.user_log import UserLog
from util.operation_yaml import OperationYaml
import re


class OperationToken:

    def __init__(self):
        self.path = FilePath()
        self.re_data = r'name="csrf-token" content="(.+?)"'
        self.token__ = 'token'
        self.token_key = 'authenticity_token'
        self.log = UserLog().get_log()
        self.op_yaml = OperationYaml()

    def get_token_dict(self,res,token_key):
        res_html = res.text
        token_dict = {}
        try:
            # token = re.findall(r'name="authenticity_token" value="(.+?)"', res_html)[0]
            # token = re.match(r'name="csrf-token" content="(.+?)"',res_html).group(0)  获取失败
            token = re.findall(self.re_data, res_html)[0]
        except:
            print("获取token失败!")
            self.log.debug("获取token失败!，返回None")
            return None
        else:
            token_dict[token_key] = token
            # print(token_dict)
            return token_dict

    def update_token(self, res):
        self.log.debug('准备更新token')
        yaml_name = self.token__
        key = self.token_key
        token_dict = self.get_token_dict(res,key)
        all_data = self.op_yaml.read_data(); update_token = all_data
        update_token[yaml_name] = token_dict
        self.log.debug('更新token成功；token为：%s' % token_dict)
        self.op_yaml.write_data(update_token)


    # 根据关键字获取数据
    def get_data(self):
        yaml_name = self.token__
        key = self.token_key
        data = self.op_yaml.read_data()[yaml_name]
        self.log.debug('根据关键字获取token')
        if key != None:
            try:
                token_value = data[key]
            except:
                self.log.error('获取token失败！data: %s没有key: "%s"' % (data, key))

            else:
                self.log.debug('获取token成功，%s' % token_value)
                return token_value


if __name__ == '__main__':
    # a01 = {'authenticity_token':'1'}
    # OperationToken().update_token(a01)
    d01 = {'authenticity_token':'11'}
    # print(OperationToken().update_token(d01))
    pass

